package com.example.demo.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.example.demo.vo.TreeNode;

public class TreeNodeUtil {
	public static List<TreeNode> listToTree(List<TreeNode> list) {
		// 用递归找子。
		List<TreeNode> treeList = new ArrayList<>();
		Iterator<TreeNode> iterator = list.iterator();
		while (iterator.hasNext()) {
			TreeNode tree = iterator.next();
			if (tree.getPid() == 0) {
				treeList.add(findChildren(tree, list));
			}
		}
		return treeList;
	}

	private static TreeNode findChildren(TreeNode tree, List<TreeNode> list) {
		Iterator<TreeNode> iterator = list.iterator();
		while (iterator.hasNext()) {
			TreeNode node = iterator.next();
			if (node.getPid() == tree.getId()) {
				if (tree.getChildren() == null) {
					tree.setChildren(new ArrayList<TreeNode>());
				}
				tree.getChildren().add(findChildren(node, list));
			}
		}
		return tree;
	}

}
